using System;
using System.Collections.Generic;
using System.Text;

namespace UserInterface.MML.Base
{
    public abstract class TagHandler
    {
        protected string GetCompiledContent(TagItem tagItem, object context)
        {
            return Compiler.GetCompiledContent(tagItem, context);
        }

        protected string GetOriginalContent(TagItem tagItem)
        {
            return Compiler.GetOriginalContent(tagItem);
        }

        public abstract string Handle(TagItem tagItem, object context);
    }

    public class BasicHTMLTagHandler : TagHandler
    {
        private bool areAttributesAllowed = false;
        private List<string> allowedAttributeNames;

        public bool AreAttributesAllowed
        {
            get { return areAttributesAllowed; }
            set { areAttributesAllowed = value; }
        }

        public List<string> AllowedAttributeNames
        {
            get { return allowedAttributeNames; }
            set { allowedAttributeNames = value; }
        }

        private bool IsAttributeAllowed(string name)
        {
            return allowedAttributeNames == null
                || allowedAttributeNames.Contains(name);
        }

        public override string Handle(TagItem tagItem, object context)
        {
            string content = GetCompiledContent(tagItem, context);
            HTMLTagBuilder tag = new HTMLTagBuilder(tagItem.Name, content);
            if (areAttributesAllowed)
            {
                foreach (TagItemAttribute attribute in tagItem.Attributes.Values)
                {
                    if (IsAttributeAllowed(attribute.Name))
                    {
                        tag.Attributes[attribute.Name] = attribute.Value;
                    }
                }
            }
            return tag.BuildRegularTag();
        }
    }
}
